package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;

import com.qianniu.napi.admin.entity.StoreItem;
import com.qianniu.napi.admin.entity.JsonDO;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.IStoreItemService;

import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.helper.HttpHelper;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.HttpUtils;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *
 * <p>
 * 门店服务项目
 * </p>
 *
 * @author chenxuebin
 * @since 2020-07-04
 */
@Controller
public class StoreItemController {

    private static final Logger logger = LoggerFactory.getLogger(StoreItemController.class);

    @Autowired
    private IStoreItemService storeitemService;
    @Autowired
    private IRedisService redisService;

    @RequestMapping("admin/storeitem/index")
    public String index() {
        return "admin/storeitem";
    }

    @RequestMapping("/admin/storeitem/list")
    @ResponseBody
    public Page<StoreItem> list(@RequestParam(value="limit",required = false) int limit,
                                @RequestParam(value="offset",required = false) int offset) {
        Wrapper<StoreItem> wrapper = new EntityWrapper<StoreItem>().eq("mpid",ObjectUtil.getMpid());
        wrapper.orderBy("sort",true);
        Page<StoreItem> page = storeitemService.selectPage(new Page<StoreItem>(offset/limit+1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/storeitem/add")
    public String add(@Valid StoreItem storeitem, BindingResult bindingResult) {
        // 字段校验
        if( bindingResult.hasErrors())
        {
            logger.debug( "There are errors! {}", bindingResult );
            return null;
        }
        storeitem.insert();
        return "admin/storeitem";
    }

    @RequestMapping("/admin/storeitem/getStoreItemById")
    @ResponseBody
    public StoreItem getStoreItemById(long id) {
        StoreItem storeitem = storeitemService.selectById(id);
        return storeitem;
    }

    @RequestMapping("/admin/storeitem/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = storeitemService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/storeitem/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        StoreItem storeitem = new StoreItem();
        storeitem.setId(id);
        storeitem.setState(state);
        storeitemService.updateById(storeitem);
        return "success";
    }

    @RequestMapping("/admin/storeitem/modify")
    public String update(StoreItem storeitem) {
        boolean isSuccc = storeitemService.updateById(storeitem);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    /// / ************* bellow is storeitem interface for user *********

    @RequestMapping("/api/storeitem/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value="status",required = false)String status,
                       @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if(pageSize==null)pageSize = 10;
        Page page=new Page(pageIndex,pageSize);
        page = storeitemService.selectPage(page, new EntityWrapper<StoreItem>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/storeitem/add")
    @ResponseBody
    public Jinfo storeitemAdd(@Valid StoreItem storeitem,
                          BindingResult bindingResult,HttpServletRequest req) {
        Jinfo info = new Jinfo();
        // 字段校验
        if(bindingResult.hasErrors())
        {
            logger.debug( "There are errors! {}", bindingResult );
            info.setMsg("There are errors! "+bindingResult);
            info.setCode(400);
            return info;
        }
        storeitem.setCreatetime(new Date());
        storeitem.insert();
        return info;
    }

    @RequestMapping("/api/storeitem/modify")
    @ResponseBody
    public Jinfo storeitemUpdate(HttpServletRequest req,
                                    StoreItem storeitem) {
        Jinfo info = new Jinfo();
        storeitem.setModifytime(new Date());
        storeitem.updateById();
        return info;
    }

    @RequestMapping("/api/storeitem/detail")
    @ResponseBody
    public Jinfo getStoreItemDetailById(@RequestParam("token") String token,
                                       @RequestParam("id") long id,HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        StoreItem storeitem = storeitemService.selectById(id);
        info.setInfo(storeitem);
        return info;
    }


    @RequestMapping("/test/yytoupiao/kaishi")
    @ResponseBody
    public JsonDO yytoupiaokaishi() {

        logger.debug("===============彦彦刷票开始===============");
        JsonDO json = new JsonDO();
        String url = "https://s1.eqxiu.com/eqs/s/scene/count?code=ul44UG5n";
        String result = "";
        redisService.set("yyshuapiao", "1");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
        long i = 0;
        while (redisService.get("yyshuapiao") != null && redisService.get("yyshuapiao").equals("1")) {

            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            formParams.add(new BasicNameValuePair("sceneId", "229494259"));
            formParams.add(new BasicNameValuePair("elementId", "6400585803"));
            formParams.add(new BasicNameValuePair("pageId", "1839061216"));
            formParams.add(new BasicNameValuePair("openid", StringUtil.getGUID()));

            result = HttpUtils.httpPost(url, formParams);
            JSONObject postinfo = JSON.parseObject(result);
            result = postinfo.getString("text");

//            logger.debug(" getTulingResult postinfo=" + postinfo.toJSONString());

//            try {
//                Thread.sleep(50);
//            } catch (Exception e) {
//            }

            i++;
            logger.debug("==========================彦彦刷票加" + i);
        }
        json.setMsg("彦彦刷票开始");
        return json;
    }

    @RequestMapping("/test/yytoupiao/jieshu")
    @ResponseBody
    public JsonDO yytoupiaojieshu() {

        logger.debug("===============彦彦刷票结束");
        JsonDO json = new JsonDO();
        redisService.set("yyshuapiao","0");
        json.setMsg("彦彦刷票结束");
        return json;
    }

}
